package net.lulihu.pangolin.headless.common.protocol.handler;


import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 协议消息类型处理程序注册
 */
@Slf4j
public class MessageTypeHandlerRegistration {

    private static final Map<Byte, MessageTypeHandler> handlerMapping = new ConcurrentHashMap<>();

    /**
     * 注册指定类型处理程序
     *
     * @param type    类型
     * @param handler 处理程序
     * @throws MessageTypeHandlerRegisteredException 如果指定类型字段已经被注册则抛出该异常
     */
    public static void register(byte type, MessageTypeHandler handler) throws MessageTypeHandlerRegisteredException {
        MessageTypeHandler absent = handlerMapping.putIfAbsent(type, handler);
        if (absent != null && handler != absent)
            throw new MessageTypeHandlerRegisteredException("消息类型[" + type + "已经被注册");
    }

    /**
     * 获取类型处理程序
     *
     * @param type 类型
     * @throws NullPointerException 如果指定类型不存在则抛出该例外
     */
    public static MessageTypeHandler getTypeHandler(byte type) throws NullPointerException {
        MessageTypeHandler handler = handlerMapping.get(type);
        if (handler == null) throw new NullPointerException("未找到类型[" + type + "]的处理程序");
        return handler;
    }


}
